import { setStorageSync, getStorageSync, removeStorageSync } from '@tarojs/taro';
import { defineStore } from 'pinia';
import { defaultExpenseTags } from '@/constants/defaultTags';
import idCreator from '@/lib/idCreator';

interface TagState {
  tagList: TagItem[];
  recordList: RecordItem[];
  tagListError: '' | 'duplicate';
  currentRecord: RecordItem | undefined;
  recordListError: '' | 'notfound';
  chosenselectOutItem: TagItem;
}

export const useTagStore = defineStore('tag-store', {
  state: (): TagState => ({
    tagList: JSON.parse(getStorageSync('tag-list') || '0') || defaultExpenseTags,
    recordList: JSON.parse(getStorageSync('record-list') || '[]'),
    tagListError: '',
    currentRecord: undefined,
    recordListError: '',
    chosenselectOutItem: defaultExpenseTags[0]
  }),
  getters: {},
  actions: {
    saveTag() {
      setStorageSync('tag-list', JSON.stringify(this.tagList));
    },
    saveRecord() {
      setStorageSync('record-list', JSON.stringify(this.recordList));
    },
    insertRecord(record: RecordItem) {
      record.id = idCreator();
      record.createAt = new Date(Date.parse(new Date()) + 60 * 60 * 1000 * 8);
      this.recordList.push(record);
      this.saveRecord();
    },
    findRecord(id: number) {
      this.currentRecord = undefined;
      const record = this.recordList.filter(item => item.id === id)[0];
      if (record) {
        this.currentRecord = record;
      }
    },
    updateRecord(payload: { id: number; record: RecordItem }) {
      const { id, record } = payload;
      let index = 0;
      for (index = 0; index < this.recordList.length; index++) {
        if (this.recordList[index].id === id) {
          this.recordList[index] = record;
          break;
        }
      }
      this.saveRecord();
    },
    removeRecord(id: number) {
      this.recordListError = '';
      let index = 0;
      for (index = 0; index < this.recordList.length; index++) {
        if (this.recordList[index].id === id) {
          break;
        }
      }
      if (index === this.recordList.length) {
        this.recordListError = 'notfound';
      } else {
        this.recordList.splice(index, 1);
        this.saveRecord();
      }
    },
    clearRecords() {
      this.recordList = [];
      this.saveRecord();
    },
    clearTags() {
      removeStorageSync('tag-list');
      this.tagList = [
        { name: 'food', value: '餐饮' },
        { name: 'shopping', value: '购物' },
        { name: 'house', value: '居住' },
        { name: 'transport', value: '交通' },
        { name: 'entertainment', value: '娱乐' },
        { name: 'medical', value: '医疗' }
      ];
      //   console.log(this.tagList);
      //   this.saveTag();
    },
    insertTag(tag: TagItem) {
      this.tagListError = '';
      const names = this.tagList.map(item => item.name);
      if (names.indexOf(tag.name) >= 0) {
        this.tagListError = 'duplicate';
      } else {
        this.tagList.push(tag);
        this.saveTag();
      }
    }
  }
});
